
import optparse
import socket
import configparser
import json

# python3 .\ftp_client.py -s 127.0.0.1 -P 8080
class ClientHandler():
    def __init__(self):
        self.op=optparse.OptionParser()

        self.op.add_option("-s", "--server", dest="server")
        self.op.add_option("-P", "--port", dest="port")
        self.op.add_option("-u", "--username", dest="username")
        self.op.add_option("-p", "--password", dest="password")
        self.options, self.args = self.op.parse_args()    
        self.verify_args(self.options, self.args)

        # 创建socket 并连接
        self.make_connection()

    def verify_args(self, options, args):
        server = options.server
        port = options.port
        username = options.username
        password = options.password
        if int(port) > 0 and int(port) < 65535:  # 端口限制
            return True
        else:
            exit("端口超出范围")

    def make_connection(self):  # 建立连接
        self.sock = socket.socket()
        self.sock.connect((self.options.server, int(self.options.port)))

    def interactive(self):
        self.authenticate()

    def authenticate(self):  # 验证
        if self.options.username is None or self.options.password is None:
            username = input("username: ")
            password = input("password: ")
            return self.get_auth_result(username, password)
        return self.get_auth_result(self.options.username, self.options.password)

    def get_auth_result(self,user,pwd):   #做验证
        data={
            "action":"auth",
            "username":user,
            "password":pwd
        }
        self.sock.send(json.dumps(data).encode("utf8"))
        data=self.sock.recv(1024).decode("utf8")
        data=json.loads(data)
        


ch=ClientHandler()
ch.interactive()
